import { Dept, Login } from "@/api/interface";
import { getAuthMenuListApi, loginApi } from "@/api/modules/login";
import { getLogo } from "@/api/modules/user";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { GlobalStore } from "@/stores";
import { AuthState } from "@/stores/interface";
import { TabsStore } from "@/stores/modules/tabs";
import { cleanDictCache, getDictTypeList } from "@/utils/cacheUtil";
import { convertMenuList, getAllBreadcrumbList, getSansanLocalMenu, getShowMenuList } from "@/utils/menuUtil";
import { getHome, setHome } from "@/utils/routerUtil";
import { getFlatArr, treeDataToList } from "@/utils/util";
import { ElMessage } from "element-plus";
import { defineStore } from "pinia";
import { PublicStore } from "./public";

// AuthStore
export const AuthStore = defineStore({
	id: "AuthState",
	state: (): AuthState => ({
		// 当前页面的 router name，用来做按钮权限筛选
		routeName: "",
		// 按钮权限列表
		authButtonList: {},
		// 菜单权限列表
		authMenuList: [],
		//本地业务系统的静态菜单：父节点菜单路径+子节点数组
		sansanRouterMap: {},
		//分组列表
		deptList: []
	}),
	getters: {
		deptListGet: state => state.deptList,
		// 按钮权限列表
		// authButtonListGet: state => state.authButtonList,
		// 后端返回的菜单列表 ==> 这里没有经过任何处理
		authMenuListGet: state => state.authMenuList,
		// 后端返回的菜单列表 ==> 左侧菜单栏渲染，需要去除 isHide == true
		showMenuListGet: state => getShowMenuList(state.authMenuList),
		// 扁平化之后的一维数组路由，主要用来添加动态路由
		flatMenuListGet: state => getFlatArr(state.authMenuList),
		// 所有面包屑导航列表
		breadcrumbListGet: state => getAllBreadcrumbList(state.authMenuList)
	},
	actions: {
		async setDeptList(value: Dept.ResDeptList[] = []) {
			this.deptList = value;
		},
		// getAuthMenuList
		async getAuthMenuList() {
			const { userInfo } = PublicStore();
			//初始本地菜单路由
			this.sansanRouterMap = await getSansanLocalMenu();

			let { result } = await getAuthMenuListApi({ username: userInfo.username });
			this.authMenuList = convertMenuList(result.records.children, this.sansanRouterMap);
		},
		getDeptIdChild(val: any) {
			let idList: string[] = [],
				nodeList: any[] = [];
			function appendChild(node: any) {
				if (node.children && node.children.length) {
					for (let i = 0; i < node.children.length; i++) {
						let child = node.children[i];
						appendChild(child);
					}
				}
				idList.push(node.id);
				nodeList.push({ ...node });
			}
			appendChild(val);
			return idList.join(",");
		},
		// 验证路由是否存在
		verifyMenu(routerUrl: string | Array<string>) {
			const objType = Object.prototype.toString.call(routerUrl);
			if (objType == "[object String]" || objType == "[object Array]") {
				let url: Array<string> = [];
				objType == "[object String]" ? (url = [routerUrl as string]) : (url = routerUrl as Array<string>);
				const list = treeDataToList(this.authMenuList).map((el: any) => el.path);
				return url.every((item: any) => list.includes(item));
			} else {
				throw "参数类型不正常，请使用string或者array";
			}
		},
		// setRouteName
		async setRouteName(name: string) {
			this.routeName = name;
		},
		async login(loginForm: Login.ReqLoginForm) {
			// const router = useRouter();
			const globalStore = GlobalStore();
			const publicStore = PublicStore();
			const tabsStore = TabsStore();
			// 1.执行登录接口
			let result: Login.ResLogin | undefined = undefined;
			try {
				const res = await loginApi({ ...loginForm });
				if (!res.success) {
					if (res.code == 204) {
						return res.message;
					}
					return ElMessage.error(res.message);
				}
				// ElMessage.success(res.message);
				result = res.result;
			} catch (e) {
				console.warn(e);
				return;
			}
			setHome(getHome());
			publicStore.setToken(result.token);
			publicStore.setUserInfo(result.user);
			publicStore.setExpire(result.expire);
			if (loginForm.rememberUser) {
				globalStore.rememberUser(loginForm.rememberUser);
			}
			if (globalStore.setting.rememberUser && loginForm.username) {
				globalStore.setting.username = loginForm.username;
			}

			// 2.获取用户个性化logo--异步
			getLogo().then(res => {
				if (res.code == 200) {
					globalStore.setLogo(res.result.logo);
					globalStore.setSystemName(res.result.systemName);
					if (res.result.home) {
						globalStore.setHome(res.result.home);
					}
				}
			});

			// 3.初始化数据字典--异步
			getDictTypeList();

			// 4.添加动态路由--同步
			await initDynamicRouter();

			// 5.清除上个账号的 tab 信息
			tabsStore.closeMultipleTab();
			return;
		},
		async logout() {
			//保留系统主题信息设置

			//清除字段缓存
			await cleanDictCache();

			//清除用户缓存
			const globalStore = GlobalStore();
			const publicStore = PublicStore();
			publicStore.setToken("");
			publicStore.setUserInfo({ username: "", userId: "" });
			globalStore.setting.home = "";
			globalStore.setting.logo = "";
			globalStore.setting.systemName = "";
		}
	}
});
